package com.szosen.device.Glucose;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.szosen.application.MyApplication;
import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.database.DBService;
import com.szosen.database.xuetang;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.util.Cache;
import com.szosen.util.TimeHelper;
import com.szosen.util.ToastTool;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.szosen.jkzj.util.Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS;

/**
 * 血糖测量
 */
public class GLU_Activity extends BaseActivity {
    private Cache cache;

    private String mDeviceName;
    private String mDeviceAddress;
    /*
     * private TextView tvaddress; private TextView tvstate;
     */
    private boolean result;
    private int tyear = 0;
    private int tmon = 0;
    private int tday = 0;
    private int thour = 0;
    private int tmin = 0;
    private int tsec = 0;
    private int xuhao = 0;
    // private Person person;
    public static Context myContext;
    // private Spinner spinner;
    private BluetoothLeService mBluetoothLeService;
    private BluetoothGattCharacteristic mNotifyCharacteristic;

    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    EditText gluse_value_et;// 血糖值
    EditText xt_data;// 时间
    TextView connect_status;// 连接状态
    ImageView glu_image;// 上传状态
    Button upload_button;
    RadioButton btn_after, btn_before;
    String from = "";
    private BluetoothAdapter mBluetoothAdapter;
    private String yibangding = "已绑定";
    String mMeasureTime = "";
    // 从哪里来的标记
    public static final String FLAG_FROM = "xuetangflag";
    public static final String FLAG_FROM_TYPE = "xuetangflag_type";
    public static final String FLAG_FROM_TYPE_BEFORE = "xuetangflag_type_before";
    public static final String FLAG_FROM_TYPE_AFTER = "xuetangflag_type_after";

    // 代码管理服务生命周期。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_measure_glucose);
        super.setTitleContent("【科诺血糖测量】");
        context = this;
        cache = new Cache(this);
        from = getIntent().getStringExtra(FLAG_FROM);
        InitView();
        mGattUpdateReceiver = new MyGattUpdateReceiver();
        makeGattUpdateIntentFilter();
        checkBTOK();
        String address = MyApplication.getCache().getDeviceAddress(Cache.GLU);
        // 开始就扫描设备。
        // scanLeDevice(true);
        if (!TextUtils.isEmpty(address)) {
            // 直连蓝牙设备。
            connect_status
                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
            connect_status.setTextColor(Color.BLUE);
            connectBT(address);
        } else {
            connect_status
                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NOBOND);
            connect_status.setTextColor(Color.BLUE);
            scanLeDevice(true);
        }
        needConnectBT = true;
    }

    public void connectDeviceAgain(View view) {
        if (connect_status.getText().toString().trim().equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS)) {
            ToastTool.showShort(context, Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS_NOTCONNECTAGAIN);
            return;
        }
        String address = MyApplication.getCache().getDeviceAddress(Cache.GLU);
        if (!TextUtils.isEmpty(address)) {
            connectBT(address);
        } else {
            ToastTool.showShort(context, "未找到已绑定设备！");
            scanLeDevice(true);
        }
    }

    TimerTask task = null;
    Timer timer = null;
    public static final int WHAT_BT_CONNECT = 9413;
    public Handler BTHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case WHAT_BT_CONNECT:
                    try {
                        String connectStatus = connect_status.getText().toString();
                        if (connectStatus
                                .equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
                            connect_status
                                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                            connect_status.setTextColor(Color.RED);
                            System.out.println("进来10秒的判断。");
                            if (mBluetoothLeService != null) {
                                mBluetoothLeService.disconnect();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }

        ;
    };

    private boolean needConnectBT = false;

    private void checkBTOK() {
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "没有蓝牙", Toast.LENGTH_SHORT).show();
            finish();
        }
        // 初始化一个蓝牙适配器。对API 18级以上，可以参考 bluetoothmanager。
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 检查是否支持蓝牙的设备。
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
    }

    private void connectBT(String address) {
        if (timer != null) {
            timer.cancel();
        }
        if (task != null) {
            task.cancel();
        }
        // 每次连接后都设计一个定时器。
        task = new TimerTask() {
            @Override
            public void run() {
                try {
                    String connectStatus = connect_status.getText().toString();
                    System.out.println("执行了10秒的计时器");
                    if (connectStatus
                            .equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
                        if (mBluetoothLeService != null) {
                            mBluetoothLeService.disconnect();
                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                connect_status
                                        .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                                connect_status.setTextColor(Color.RED);
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer = new Timer();
        timer.schedule(task, 10000L);
        // mDeviceAddress = cache.getDeviceAddress("Carenovo");
        // 之前连接过的地址。
        mDeviceAddress = address;
        if (mDeviceAddress != null && mDeviceAddress.length() > 0) {
            connect_status
                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
            connect_status.setTextColor(Color.BLUE);
            System.out.println(mDeviceAddress);
            if (mGattUpdateReceiver != null) {
                try {
                    unregisterReceiver(mGattUpdateReceiver);
                    unbindService(mServiceConnection);
                    // mBluetoothLeService.disconnect();
                } catch (Exception e) {
                }
            } else {
            }
            // 注册蓝牙连接服务。
            mGattUpdateReceiver = new MyGattUpdateReceiver();
            registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
            Intent gattServiceIntent = new Intent(GLU_Activity.this,
                    BluetoothLeService.class);
            bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
            // clearAllList();
            // if (mDeviceDialog != null && mDeviceDialog.isShowing()) {
            // mDeviceDialog.dismiss();
            // }
        } else {
            scanLeDevice(true);
            // 提示连接失败。
        }
    }

    boolean mScanning;
    int destoryFlag = 0;
    BluetoothDevice mDevice = null;
    Runnable mRunnable = null;

    @SuppressWarnings("deprecation")
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // 停止后一个预定义的扫描周期扫描。
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    // mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    mScanning = false;
                    // mHandler.postDelayed(mRunnable, 3000);
                    // 不发送handler。只扫描一次。
                    System.out.println("3秒后执行一次扫描！");
                    if (destoryFlag == 1) {
                        mHandler.removeCallbacks(this);
                        System.out.println("清除执行");
                        return;
                    }
                    mBluetoothAdapter.startLeScan(mLeScanCallback);
                }
            };
            mHandler.postDelayed(mRunnable, 1000);
            // 延时一秒来发送handler
            mScanning = true;
            // mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }

    // 扫描装置的回调。
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             byte[] scanRecord) {
            if (destoryFlag == 1) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // if (device.getName() != null
                    // && device.getName().contains("arenovo")) {
                    // mDevice = device;
                    // destoryFlag = 1;
                    // System.out.println("名字" + device.getName());
                    // System.out.println("获取设备");
                    // HashMap<String, Object> map = new HashMap<String,
                    // Object>();
                    // map.put("name", device.getName());
                    // map.put("andrass", device.getAddress());
                    // map.put("device", device);
                    // String address = device.getAddress();
                    // System.out.println("扫描到了蓝牙地址：" + mDeviceAddress);
                    // mDeviceAddress = address;
                    // connectBT(mDeviceAddress);
                    // }
                    // 扫描
                    if (device.getName() != null
                            && device.getName().contains("arenovo")) {
                        String defaultAddress = MyApplication.getCache()
                                .getDeviceAddress(Cache.GLU);
                        if (!TextUtils.isEmpty(defaultAddress)
                                && defaultAddress.equals(device.getAddress())) {
                            addData(device.getName() + "(" + yibangding + ")",
                                    device.getAddress());
                            System.out.println("已绑定名字" + device.getName());
                            mDevice = device;
                            mDeviceAddress = device.getAddress();
                            System.out.println("获取设备mac地址" + mDeviceAddress);
                            // registerReceiver(mGattUpdateReceiver,
                            // makeGattUpdateIntentFilter());
                            // Intent gattServiceIntent = new Intent(
                            // GLU_Activity.this, BluetoothLeService.class);
                            // bindService(gattServiceIntent,
                            // mServiceConnection,
                            // BIND_AUTO_CREATE);
                            // connectBT(mDeviceAddress);
                        } else {
                            addData(device.getName(), device.getAddress());
                        }
                        // 如果第一次使用，没绑定过设备。
                        if (TextUtils.isEmpty(defaultAddress)) {
                            // 这里需要增加一个蓝牙的列表。然后点击后就得到这个设备，然后连接。

                        }
                    }
                }
            });
        }
    };
    private MyAdapter mMyAdapter;
    ArrayList<String[]> deviceMacList = new ArrayList<String[]>();

    private void addData(String name, String mac) {
        System.out.println("增加了 设备" + name + mac);
        boolean isHas = false;
        for (int i = 0; i < deviceMacList.size(); i++) {
            String[] item = deviceMacList.get(i);
            String m = item[1];
            if (m.equals(mac)) {
                isHas = true;
            }
        }
        if (!isHas) {
            deviceMacList.add(new String[]{name, mac});
        }
        // 通知更新listView
        if (mMyAdapter != null) {
            mMyAdapter.notifyDataSetChanged();
        }
    }

    String this_bt_name = "", this_bt_mac = "";

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(GLU_Activity.this);
        LayoutInflater inflater = (LayoutInflater) GLU_Activity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activity_tiwen_dialog_chancedevice, null);
        final ListView lv_btdevice_lists = (ListView) tl
                .findViewById(R.id.lv_btdevice_lists);
        final LinearLayout ll_password = (LinearLayout) tl
                .findViewById(R.id.ll_tiwen_password);
        final EditText et_password = (EditText) ll_password
                .findViewById(R.id.et_tiwen_password);
        mMyAdapter = new MyAdapter(deviceMacList);
        lv_btdevice_lists.setAdapter(mMyAdapter);

        lv_btdevice_lists.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 点击一个蓝牙设备，就设定连接这个设备
                // 设置显示修改设备
                // 先把已经连接的取消。再连接新的。
                String[] item = (String[]) parent.getAdapter()
                        .getItem(position);
                System.out.println("蓝牙名称：" + item[0] + ",蓝牙mac地址：" + item[1]);
                this_bt_name = item[0];
                this_bt_mac = item[1];
                if (!item[0].contains(yibangding)) {
                    ll_password.setVisibility(View.VISIBLE);
                } else {
                    connectBT(this_bt_mac);
                }
                // scanLeDevice(false);

            }
        });
        builder.setView(tl);
        builder.setTitle("请选择蓝牙设备：");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (ll_password.getVisibility() != View.VISIBLE) {
                    return;
                }
                String password = et_password.getText().toString();
                if (!TextUtils.isEmpty(password)
                        && BluetoothListActivity.changeDevicePassword
                        .equals(password)) {
                    // 把蓝牙设备列表清除。重新找设备。
                    clearAllList();
                    connectBT(this_bt_mac);
                } else {
                    ToastTool.showShort(context, "密码不正确！");
                }
                // scanLeDevice(false);
            }
        });
        builder.setNegativeButton("取消", null);
        mDeviceDialog = builder.create();
        mDeviceDialog.show();
    }

    private AlertDialog mDeviceDialog = null;

    private void clearAllList() {
        if (deviceMacList != null) {
            deviceMacList.clear();
        }
    }

    class MyAdapter extends BaseAdapter {
        private ArrayList<String[]> mList = new ArrayList<String[]>();

        MyAdapter(ArrayList<String[]> list) {
            mList = list;
        }

        public void addData(String name, String mac) {
            boolean isHas = false;
            for (int i = 0; i < mList.size(); i++) {
                String[] item = mList.get(i);
                String m = item[1];
                if (m.equals(mac)) {
                    isHas = true;
                }
            }
            if (!isHas) {
                mList.add(new String[]{name, mac});
            }
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public String[] getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            // 只有为空时才构造
            if (convertView == null) {
                holder = new Holder();
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        R.layout.tiwen_listview_item_layout, null);
                holder.tv_name = (TextView) convertView
                        .findViewById(R.id.tiwen_listview_item_tv_name);
                holder.tv_mac = (TextView) convertView
                        .findViewById(R.id.tiwen_listview_item_tv_mac);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            String[] s = mList.get(position);
            holder.tv_name.setText(s[0]);
            holder.tv_mac.setText(s[1]);
            return convertView;
        }

        class Holder {
            TextView tv_name;// 蓝牙名字
            TextView tv_mac;// mac地址
        }

    }

    /**
     * 销毁广播接收器
     */
    @Override
    protected void onPause() {
        super.onPause();
        try {
            // unregisterReceiver(mGattUpdateReceiver);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * 注册广播
         */
        try {
            registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
            if (mBluetoothLeService != null) {
                Log.e("a", "来了");
                result = mBluetoothLeService.connect(mDeviceAddress);
                Log.e("a", "连接请求的结果=" + result);
            }
        } catch (Exception e) {
            Log.e("err", "005");
        }
    }

    @Override
    public void onBackPressed() {
        String connectStatus = connect_status.getText().toString();
        if (connectStatus
                .equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
            ToastTool.showLong(context, "正在连接设备，请勿退出!");
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 结束服务
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryFlag = 1;
        try {
            // 注销接收广播
            unregisterReceiver(mGattUpdateReceiver);
            isStopService = true;
            unbindService(mServiceConnection);
            mBluetoothLeService.disconnect();
            mBluetoothLeService.close();
            // 停止扫描
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mHandler.removeCallbacks(mRunnable);
            System.out.println("血糖移除handler消息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化控件
     */
    private void InitView() {
        gluse_value_et = (EditText) findViewById(R.id.gluse_value_et);
        xt_data = (EditText) findViewById(R.id.xt_data);
        String time = TimeHelper.getCurrentTime();
        xt_data.setText(time);
        connect_status = (TextView) findViewById(R.id.connect_status);
        glu_image = (ImageView) findViewById(R.id.glu_image);
        upload_button = (Button) findViewById(R.id.upload_button);
        btn_before = (RadioButton) findViewById(R.id.btn_before);
        btn_before.setChecked(true);
        btn_after = (RadioButton) findViewById(R.id.btn_after);
        if (!TextUtils.isEmpty(from) && "jktj".equals(from)) {
            upload_button.setText("确定");
        }
        String type = getIntent().getStringExtra(FLAG_FROM_TYPE);
        if (FLAG_FROM_TYPE_AFTER.equals(type)) {
            btn_after.setChecked(true);
        } else if (FLAG_FROM_TYPE_BEFORE.equals(type)) {
            btn_before.setChecked(true);
        }
        findViewById(R.id.ll_ua).setVisibility(View.GONE);
        findViewById(R.id.ll_chol).setVisibility(View.GONE);
        Button find_device = (Button) findViewById(R.id.find_device);
        find_device.setText("绑定设备");
        find_device.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 选择低功耗蓝牙的名称，然后记录。
                // 点击查找设备后扫描
                scanLeDevice(true);
                showDialog();
            }
        });
        upload_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 离线保存 */
                try {
                    upload();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static final int result_Code = 6;

    private void upload() throws Exception {
        String glu = gluse_value_et.getText().toString();
        String gluDate = xt_data.getText().toString();
        if (!TextUtils.isEmpty(from) && "jktj".equals(from)) {
            Intent data = new Intent();
            // glu = 66 + "";
            data.putExtra("glu", glu);
            if (btn_after.isChecked()) {
                data.putExtra(FLAG_FROM_TYPE, FLAG_FROM_TYPE_AFTER);
            } else if (btn_before.isChecked()) {
                data.putExtra(FLAG_FROM_TYPE, FLAG_FROM_TYPE_BEFORE);
            }
            setResult(result_Code, data);
            finish();
            return;
        } else if (glu.length() > 0) {// 葡萄糖有数据，可以上传
            xuetang uploadBean = new xuetang();
            uploadBean.setIdCard(BaseActivity.getIdCard());
            uploadBean.setTime(gluDate);
            uploadBean.setGlu(glu);
            if (btn_before.isChecked()) {
                uploadBean.setBeforeafter("前");
            } else {
                uploadBean.setBeforeafter("后");
            }
            boolean b = DBService.add(uploadBean);
            if (b) {
                ToastTool.showLong(context, "数据保存成功");
            } else {
                ToastTool.showLong(context, "数据保存失败");
            }
        }
    }

    /**
     * @param b byte[]
     * @return String
     */
    public static String Bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }

    /**
     * 将两个ASCII字符合成一个字节； 如："EF"–> 0xEF
     *
     * @param src0 byte
     * @param src1 byte
     * @return byte
     */
    @SuppressLint("DefaultLocale")
    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0}))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1}))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    /**
     * 将指定字符串src，以每两个字符分割转换为16进制形式 如："2B44EFD9" –> byte[]{0x2B, 0x44, 0xEF,
     * 0xD9}
     *
     * @param src String
     * @return byte[]
     */
    public static byte[] HexString2Bytes(String src) {
        byte[] ret = new byte[src.length() / 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < src.length() / 2; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }

    public int CheckSum(byte[] buf, int length) {
        int sum = 0;
        for (int i = 0; i < length; i++)
            sum += 0xff & buf[i];
        return sum;
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        // intentFilter.addAction(BluetoothLeService.ACTION_RSSI);
        // intentFilter.addAction(BluetoothLeService.ACTION_DATA_RSSI);
        return intentFilter;
    }

    // 连接服务。
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service) {
            try {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                        .getService();
                if (!mBluetoothLeService.initialize()) {
                    finish();
                }
                // 自动连接到装置上成功启动初始化。
                result = mBluetoothLeService.connect(mDeviceAddress);
                System.out.println("连接结果：" + mDeviceAddress + "," + result);
                MyApplication.getCache().saveDeviceAddress(Cache.GLU,
                        mDeviceAddress);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("001");
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            try {
                mBluetoothLeService.disconnect();
                mBluetoothLeService = null;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.err.println("002");
            }
        }
    };

    /*
     * 判断字符串是否包含一些字符 contains
     */
    public static boolean containsString(String src, String dest) {
        boolean flag = false;
        if (src.contains(dest)) {
            flag = true;
        }
        return flag;
    }

    private boolean isStopService = false;

    // 处理各种事件的服务了。
    // action_gatt_connected连接到服务器：关贸总协定。
    // action_gatt_disconnected：从关贸总协定的服务器断开。
    // action_gatt_services_discovered：关贸总协定的服务发现。
    // action_data_available：从设备接收数据。这可能是由于阅读
    // 或通知操作。
    private class MyGattUpdateReceiver extends BroadcastReceiver {
        private boolean WoShouYingDa = false;
        private String BTRDATA = null;
        private String BTRDATA2 = null;

        @Override
        public void onReceive(Context context, Intent intent) {

            try {
                final String action = intent.getAction();
                if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                    result = true;
                    Log.e("a", "来了广播1");
                    getWindow().invalidatePanelMenu(
                            Window.FEATURE_OPTIONS_PANEL);
                } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                        .equals(action)) {
                    result = false;
                    mDevice = null;
                    Log.e("a", "来了广播2");
                    // tvstate.setText("未连接");
                    // unregisterReceiver(mGattUpdateReceiver);
                    isStopService = true;
                    // unbindService(mServiceConnection);
                    // mBluetoothLeService.disconnect();
                    // mBluetoothLeService.close();
                    // scanLeDevice(true);
                    connect_status
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                    connect_status.setTextColor(Color.RED);
                    BTRDATA = "";
                } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                        .equals(action)) {
                    // WoShouYingDa = false;
                    // 显示所有的支持服务的特点和用户界面。
                    connect_status
                            .setText(BLUETOOTH_CONNECTSUCCESS);
                    connect_status.setTextColor(Color.BLUE);
                    cache.saveDeviceAddress("Carenovo", mDeviceAddress);
                    displayGattServices(mBluetoothLeService
                            .getSupportedGattServices());
                    Log.e("a", "来了广播3");
                    // List<BluetoothGattService> supportedGattServices =
                    // mBluetoothLeService.getSupportedGattServices();
                    displayGattServices(mBluetoothLeService
                            .getSupportedGattServices());
                    // for (int i = 0; i < supportedGattServices.size(); i++) {
                    // Log.e("a", "1:BluetoothGattService UUID=:" +
                    // supportedGattServices.get(i).getUuid());
                    // List<BluetoothGattCharacteristic> cs =
                    // supportedGattServices.get(i).getCharacteristics();
                    // for (int j = 0; j < cs.size(); j++) {
                    // Log.e("a", "2: BluetoothGattCharacteristic UUID=:" +
                    // cs.get(j).getUuid());
                    //
                    // List<BluetoothGattDescriptor> ds =
                    // cs.get(j).getDescriptors();
                    // for (int f = 0; f < ds.size(); f++) {
                    // Log.e("a", "3: BluetoothGattDescriptor UUID=:" +
                    // ds.get(f).getUuid());
                    //
                    // byte[] value = ds.get(f).getValue();
                    //
                    // Log.e("a", "4: value=:" + Arrays.toString(value));
                    // Log.e("a", "5: value=:"
                    // +
                    // Arrays.toString(ds.get(f).getCharacteristic().getValue()));
                    // }
                    // }
                    // }

                } else if (BluetoothLeService.ACTION_DATA_AVAILABLE
                        .equals(action)) {

                    // if (result)
                    // btitem.setIcon(R.drawable.ic_action_bluetooth_connected);
                    // else
                    // btitem.setIcon(R.drawable.ic_action_bluetooth_searching);
                    // --------------------------------------------------------------------------------------------------------------------//
                    if (WoShouYingDa)
                        BTRDATA += intent
                                .getStringExtra(BluetoothLeService.EXTRA_DATA);
                    else {
                        BTRDATA = intent
                                .getStringExtra(BluetoothLeService.EXTRA_DATA);
                    }
                    byte[] RDATAM = new byte[64];
                    System.out.println("收到了数据：" + BTRDATA);
                    RDATAM = BTRDATA.getBytes();
                    /* tvdata.setText(RDATA ); */
                    // 握手数据
                    if (containsString(BTRDATA, "Hello")) {
                        mBluetoothLeService.write(mNotifyCharacteristic,
                                "Hello");
                        BTRDATA = "";
                        // tvdata.setText("ID号为：" + mDeviceName.substring(8, 17)
                        // + "测试通过");
                    } else if
                        // (containsString(BTRDATA,"aa09100aa5b4c3d203bb"))
                            (BTRDATA.equals("aa09100aa5b4c3d203bb"))
                    // (RDATAM[0] == 'a' && RDATAM[1] == 'a' && RDATAM[2] == '0'
                    // && RDATAM[3] == '9' && RDATAM[4] == '1'
                    // && RDATAM[5] == '0')
                    {
                        int length = 12;
                        byte[] buf = new byte[length];
                        buf[6] = (byte) 0x2d;
                        buf[7] = (byte) 0x3c;
                        buf[8] = (byte) 0x4b;
                        buf[9] = (byte) 0x5a;
                        buf[4] = (byte) 0x80;
                        buf[5] = (byte) 0x01;
                        buf[0] = (byte) 0xaa;
                        buf[1] = (byte) 0x0a;
                        buf[2] = (byte) 0x10;
                        buf[3] = (byte) length;
                        int chk = CheckSum(buf, length - 2);
                        buf[length - 2] = (byte) ((0xff00 & chk) >> 8);
                        buf[length - 1] = (byte) (0xff & chk);

                        Log.d("glu", "蓝牙模块握手信息：" + BTRDATA);
                        /*
                         * mBluetoothLeService.write(mNotifyCharacteristic,
						 * Bytes2HexString(buf).substring(0, 11));
						 * mBluetoothLeService.write(mNotifyCharacteristic,
						 * Bytes2HexString(buf).substring(12, 23));
						 */
                        // 握手数据应答AA0A100C80012D3C4B5A025F
                        mBluetoothLeService.write(mNotifyCharacteristic,
                                "AA0A100C80012D3C4B5A");
                        mBluetoothLeService
                                .write(mNotifyCharacteristic, "025F");
                        WoShouYingDa = true;
                        Log.d("glu", "手机接收握手信息应答：AA0A100C80012D3C4B5A025F");
                        BTRDATA = "";

                    }
                    // 血糖数据
                    else if (containsString(BTRDATA, "AA091115")
                            && (BTRDATA.length() == 42))
                    // ((BTRDATA.length() == 42) && RDATAM[0] == 'A' &&
                    // RDATAM[1] == 'A' && RDATAM[2] == '0'
                    // && RDATAM[3] == '9' && RDATAM[4] == '1' && RDATAM[5] ==
                    // '1')
                    {
                        Log.d("glu", "蓝牙模块数据信息：" + BTRDATA);
                        int length = 16;
                        byte[] buf = new byte[length];

                        byte[] RDATAM2 = new byte[21];
                        RDATAM2 = HexString2Bytes(BTRDATA);

                        tyear = (0xff & RDATAM2[4]) * 256 + (0xff & RDATAM2[5]);
                        tmon = 0xff & RDATAM2[6];
                        tday = 0xff & RDATAM2[7];
                        thour = 0xff & RDATAM2[8];
                        tmin = 0xff & RDATAM2[9];
                        tsec = 0xff & RDATAM2[10];
                        Calendar MyCalendar = Calendar.getInstance();
                        buf[6] = (byte) ((0xff00 & MyCalendar
                                .get(Calendar.YEAR)) >> 8);
                        buf[7] = (byte) (0xff & MyCalendar.get(Calendar.YEAR));
                        buf[8] = (byte) (MyCalendar.get(Calendar.MONTH) + 1);
                        buf[9] = (byte) MyCalendar.get(Calendar.DAY_OF_MONTH);
                        buf[10] = (byte) MyCalendar.get(Calendar.HOUR_OF_DAY);
                        buf[11] = (byte) MyCalendar.get(Calendar.MINUTE);
                        buf[12] = (byte) MyCalendar.get(Calendar.SECOND);
                        buf[13] = (byte) 0x00;
                        buf[4] = (byte) 0x80;
                        buf[5] = (byte) 0x01;
                        buf[0] = (byte) 0xaa;
                        buf[1] = (byte) 0x0a;
                        buf[2] = (byte) 0x11;
                        buf[3] = (byte) length;
                        int chk = CheckSum(buf, length - 2);
                        buf[length - 2] = (byte) ((0xff00 & chk) >> 8);
                        buf[length - 1] = (byte) (0xff & chk);

						/*
						 * mBluetoothLeService.write(mNotifyCharacteristic,
						 * "AA0A1110800107DF");AA0A1110800107DF0A0814032600028B
						 * mBluetoothLeService.write(mNotifyCharacteristic,
						 * "0A0814032600028B");
						 */

                        // 血糖数据应答
                        String GLUDataH = Bytes2HexString(buf).substring(0, 20);
                        mBluetoothLeService.write(mNotifyCharacteristic,
                                GLUDataH);
                        String GLUDataL = Bytes2HexString(buf)
                                .substring(20, 32);
                        mBluetoothLeService.write(mNotifyCharacteristic,
                                GLUDataL);
                        RDATAM = HexString2Bytes(BTRDATA);
                        Log.d("glu", "手机接收数据信息应答：" + Bytes2HexString(buf));
						/*
						 * tvdata.setText(BTRDATA + "\nGLU:" + ((float)
						 * ((RDATAM[12] & 0xff) * 256 + RDATAM[13] & 0xff)) / 10
						 * + "mmol/L");
						 */

                        String Buffer = String.valueOf(xuhao)
                                + ":  "
                                + String.valueOf(tyear)
                                + "-"
                                + String.valueOf(tmon)
                                + "-"
                                + String.valueOf(tday)
                                + " "
                                + String.valueOf(thour)
                                + ":"
                                + String.valueOf(tmin)
                                + ":"
                                + String.valueOf(tsec)
                                + " "
                                + String.valueOf(((float) (((RDATAM[12] & 0xff) << 8) | (RDATAM[13] & 0xff))) / 10)
                                + "mmol/L" + "\r\n";

                        String Bufferc = ":  "
                                + String.valueOf(tyear)
                                + "-"
                                + String.valueOf(tmon)
                                + "-"
                                + String.valueOf(tday)
                                + " "
                                + String.valueOf(thour)
                                + ":"
                                + String.valueOf(tmin)
                                + ":"
                                + String.valueOf(tsec)
                                + " "
                                + String.valueOf(((float) (((RDATAM[12] & 0xff) << 8) | (RDATAM[13] & 0xff))) / 10)
                                + "mmol/L" + "\r\n";
                        if ((BTRDATA2 != null)
                                && (containsString(BTRDATA2, Bufferc) == false)) {
                            ++xuhao;
                            BTRDATA2 += Buffer;

                        } else if (BTRDATA2 == null) {
                            ++xuhao;
                            BTRDATA2 = Buffer;

                        }
                        // 设置血糖值。
                        String xuetangzhi = String
                                .valueOf(((float) (((RDATAM[12] & 0xff) << 8) | (RDATAM[13] & 0xff))) / 10);
                        System.out.println("");
                        // 当前的时间。
                        String realTime = TimeHelper.getCurrentTime();
                        // 如果时间为空就设置为最新的时间，如果时间的除了最后一位其他相同，就没事，（秒数个位不同，其他都相同，），不然就设置成最新的了
                        if (TextUtils.isEmpty(mMeasureTime)) {
                            mMeasureTime = realTime;
                        } else {
                            String readTStr = realTime.substring(0,
                                    realTime.length() - 1);
                            String MeasureTimeStr = mMeasureTime.substring(0,
                                    realTime.length() - 1);
                            if (!readTStr.equals(MeasureTimeStr)) {
                                mMeasureTime = realTime;
                            }
                        }
                        xt_data.setText(mMeasureTime);
                        gluse_value_et.setText(xuetangzhi);
                        BTRDATA = "";
                        // BTRDATA2="";
                        RDATAM = HexString2Bytes(BTRDATA);
                        // Toast.makeText(getApplicationContext(), "本次测量完成！",
                        // Toast.LENGTH_SHORT).show();
                        // 关机指令发送
                        boolean b = mBluetoothLeService.write(
                                mNotifyCharacteristic, "aa0a1200000000c6");
                        System.out.println("发送关机的指令成功。" + b);
                    }
                    // 关机指令；
                    else if ((BTRDATA.length() == 16) && RDATAM[0] == 'A'
                            && RDATAM[1] == 'A' && RDATAM[2] == '0'
                            && RDATAM[3] == '9' && RDATAM[4] == '1'
                            && RDATAM[5] == '2') {
                        System.out.println("接受的数据：" + BTRDATA);
                        mBluetoothLeService.write(mNotifyCharacteristic,
                                "aa0a1200000000c6");
                    }
                    // 关机指令；
                    // else if((BTRDATA.length() == 16) && RDATAM[0] == 'A' &&
                    // RDATAM[1] == 'A' && RDATAM[2] == '0'
                    // && RDATAM[3] == '9' && RDATAM[4] == '1' && RDATAM[5] ==
                    // '2')
                    // {
                    //
                    // mBluetoothLeService.write(mNotifyCharacteristic,
                    // "aa0a1200000000c6");
                    // Thread.sleep(1000);//延时一会，等待接收完成
                    // Toast.makeText(getApplicationContext(), "本次测量完成！",
                    // Toast.LENGTH_SHORT).show();
                    // try {
                    // mBluetoothLeService.disconnect();
                    // } catch (Exception e) {
                    // // TODO Auto-generated catch block
                    // System.err.println("006");
                    // }
                    //
                    // System.err.println(BTRDATA);
                    // BTRDATA = "";
                    // // Intent intent2 =new
                    // Intent(BluetoothControlActivity.this,MainActivity.class);
                    // // startActivity(intent2);
                    // finish();
                    // }
                    // --------------------------------------------------------------------------------------------------------------------//
                }
            } catch (Exception e) {
                Log.e("err", "003");
            }
        }
    }

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = "service_UUID";
        String unknownCharaString = "characteristic_UUID";
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // 循环遍历服务
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put("NAME",
                    SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put("UUID", uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();
            charas = new ArrayList<BluetoothGattCharacteristic>();

            // 循环遍历特征
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put("NAME",
                        SampleGattAttributes.lookup(uuid, unknownCharaString));
                currentCharaData.put("UUID", uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }

        final BluetoothGattCharacteristic characteristic = charas.get(charas
                .size() - 1);
        final int charaProp = characteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            if (mNotifyCharacteristic != null) {
                mBluetoothLeService.setCharacteristicNotification(
                        mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
            }
            mBluetoothLeService.readCharacteristic(characteristic);

        }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            mNotifyCharacteristic = characteristic;
            mBluetoothLeService.setCharacteristicNotification(characteristic,
                    true);
        }

		/*
		 * SimpleExpandableListAdapter gattServiceAdapter = new
		 * SimpleExpandableListAdapter( this, gattServiceData,
		 * android.R.layout.simple_expandable_list_item_2, new String[] {"NAME",
		 * "UUID"}, new int[] { android.R.id.text1, android.R.id.text2 },
		 * gattCharacteristicData,
		 * android.R.layout.simple_expandable_list_item_2, new String[] {"NAME",
		 * "UUID"}, new int[] { android.R.id.text1, android.R.id.text2 } );
		 * mGattServicesList.setAdapter(gattServiceAdapter);
		 */
    }

    private ExpandableListView mGattServicesList;
    private ArrayList<BluetoothGattCharacteristic> charas;

    private MyGattUpdateReceiver mGattUpdateReceiver;
}